<?php

namespace App\Admin\Console\Commands;

use App\Admin\Models\SystemModel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;

class MakeUpCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = '
        admin:make-up
        {--force : 强制更新}
    ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新模型配置、前台资源和后台资源';

    public static $updateConfirmTip = '对应的模型配置、前台资源和后台资源已存在，是否更新？';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {   
        if (config()->get('app.env')=='production') {
            $this->warn('生产环境下不适用');
            return false;
        }
        $requiredFields = array_unique(array_merge(
            SystemModel::$searchHideField,
            SystemModel::$listReturnField,
            SystemModel::$formHideField,
            SystemModel::$detailHideField
        ));
        $systemModels = SystemModel::withTrashed()
            ->where('parent_id',0)
            // 如果是系统模型，则忽略
            ->whereNotIn('slug',array_keys(SystemModel::$systemModels))
            ->get(['slug','name'])
            ->toArray();
        foreach ($systemModels as $systemModel) {
            // 如果缺少必要字段，则忽略
            if (Schema::hasColumns($systemModel['slug'], $requiredFields)) {
                $title = rtrim($systemModel['name'],'表');
                if (!$this->option('force') && !$this->confirm("[ {$title} ] ".static::$updateConfirmTip, true)){
                    return false;
                }
                $this->info("更新模型 [ {$title} ]");
                Artisan::call("admin:make-model ".$systemModel['slug'].' --force');
                $this->info("更新前台 [ {$title} ]");
                Artisan::call("home:make-resource ".$systemModel['slug'].' --force');
                $this->info("更新后台 [ {$title} ]");
                Artisan::call("admin:make-resource ".$systemModel['slug'].' --force');
            }
        }
    }
}
